<template>
  <div class="bg-white m-4 mr-0 overflow-hidden">
    <BasicTree
      title="数据源列表"
      toolbar
      search
      :clickRowToExpand="false"
      :treeData="treeData"
      @select="handleSelect"
    />
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, ref } from 'vue';

  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { getDataSourceList } from '/@/api/gen/dataSource';
  import { DataSourceListGetResultModel } from '/@/api/gen/model/DataSourceModel';

  const treeData = ref<TreeItem[]>([]);
  const dataSourceList = ref<DataSourceListGetResultModel>([]);
  const emit = defineEmits(['select']);

  async function fetch() {
    treeData.value = (await getTreeData()) as unknown as TreeItem[];
  }

  //将数据与列表转换为树结构
  async function getTreeData() {
    dataSourceList.value = await getDataSourceList();
    const tree = [] as unknown as TreeItem[];
    dataSourceList.value.forEach((dataSource) => {
      let treeItem = tree.find((tree) => tree?.title === dataSource.dbType);
      const treeChild = {
        title: dataSource.dbName,
        key: dataSource.dbinfoId,
        dataSource: dataSource,
      };

      if (!treeItem) {
        treeItem = {
          title: dataSource.dbType,
          key: dataSource.dbType,
          children: [treeChild],
        };
        tree.push(treeItem);
      } else {
        treeItem.children?.push(treeChild);
      }
    });

    return tree;
  }

  function handleSelect(keys: number[]) {
    const dataSource = dataSourceList.value.find((ds) => ds.dbinfoId === keys[0]);
    if (!dataSource) {
      return;
    }
    emit('select', dataSource);
  }
  onMounted(() => {
    fetch();
  });
</script>
